/**
 * Copyright © 2011 looty - Textoo
 * @link http://www.textoo.org
 * @link http://code.google.com/p/textoo/
 * @author lab9 - Bertrand Larrieu
 * @mail lab9.fr@gmail.com
 * @version 2.0
 */

package org.looty.core.textoo.render 
{
	import flash.display.*;
	import flash.geom.*;
	import flash.text.*;
	import org.looty.core.textoo.format.*;
	import org.looty.core.textoo.render.glyph.*;
	import org.looty.textoo.events.*;
	import org.looty.textoo.render.*;

	public class SplittedBitmapRenderer extends AbstractTextooRenderer implements ITextooRenderer
	{
		
		private var _glyphManager		:GlyphManager;		
		private var _textField			:TextField;
		
		public function SplittedBitmapRenderer() 
		{
			super(4);
			_glyphManager = new GlyphManager();
			_textField = createTextField();
		}
		
		override protected function applyProperties(textField:TextField, props:TextooProps):void 
		{
			_textField.text = "";
			super.applyProperties(textField, props);
		}
		
		public function render(props:TextooProps):RenderData 
		{
			applyProperties(_textField, props);
			
			var displayObjects:Vector.<DisplayObject> = new Vector.<DisplayObject>();
			var letters:Vector.<ILetter> = new Vector.<ILetter>(props.length);
			var i:int;
			var char:String;
			var table:GlyphTable;
			var bd:Rectangle;
			var glyph:GlyphBitmapData;
			var letter:BitmapLetter;
			var definition:Class = props.bitmapLetterClass || BitmapLetter;
			
			all:for each (var textRun:TextRun in _textField.getTextRuns())
			{
				
				table = _glyphManager.getTable(textRun.textFormat, props.useDeviceFonts, props.isTextLightType, props.sharpness, props.thickness);
				
				run:for (i = textRun.beginIndex; i < textRun.endIndex; ++i)
				{
					if (i >= props.length) break all;
					
					char = props.text.charAt(i);
					if (/\s/.test(char)) continue run;
					
					bd = _textField.getCharBoundaries(i);
					
					glyph = table.getGlyph(char);
					if (glyph == null || bd == null) continue run;
					
					letter = new definition()
					letter.construct(glyph, uint(textRun.textFormat.color), bd);
					
					displayObjects.push(letter);
					letters[i] = letter;
					
				}
			}
			
			_textField.text = "";
			
			return new RenderData(displayObjects, letters, null);
		}
		
	}

}